package c3g;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;

import java.io.*;
import java.util.ArrayList;
import java.util.Properties;

public class SqlConfig {
    private ArrayList<Item> list =new ArrayList<Item>();
    private String value;
    public void ReadConfig(Item item1, File f)throws IOException {
        Properties props =new Properties();
        BufferedReader reader=null;
        reader=new BufferedReader(new FileReader(f));
        String temp;
        while (( temp=reader.readLine())!=null){
            Item item =new Item();
            String filename[]=f.getName().split("\\.");
            item1.setTablename(filename[0]);
            //判断是否为message
            String ismessage =temp.split("=")[0];
            if (!ismessage.equals("message")) {
                item.setName(ismessage);
                InputStream in = new BufferedInputStream(new FileInputStream(f));
                props.load(new InputStreamReader(in,"UTF-8"));
                value =props.getProperty(item.getName());
                String all[] =value.split(",");
                if(all.length==4){
                    item.setIskey(all[3]);
                }
                if(all.length<3)
                {
                    System.out.println("格式为字段名=字段类型，字段注释，字段大小，（若需添加KEY或PRIMARY KEY）KEY类型");
                    break;
                }
                item.setType(all[0]);
                item.setNote(all[1]);
                item.setSize(all[2]);
                this.list.add(item);
            }
            item1.setMassage(props.getProperty("message"));
        }
//        }
        reader.close();
    }
    public void build(Item item,String path,String vmpath)throws IOException{

        //设置模板、容器
        VelocityEngine ve =new VelocityEngine();
        VelocityContext velocityContext =new VelocityContext();  //生成对象
        ve.init();
        Template template =ve.getTemplate(vmpath);   //设置模板文件
        velocityContext.put("item",item);  //设置容器
        velocityContext.put("list",this.list);
        StringWriter stringWriter =new StringWriter();
        template.merge(velocityContext,stringWriter);
        String r =stringWriter.toString();
        File desfile =new File(path+item.getTablename()+".java");
        if(!desfile.exists()){
            desfile.createNewFile();
        }
        Writer wr = null;
        wr = new FileWriter(desfile);
        wr.append(r);
        wr.flush();
        wr.close();
    }
    public String getValue() {
        return value;
    }
    public void setValue(String value) {
        this.value = value;
    }
}
